/**
 * 易驰护运 - Register
 * http://menger.me
 * 注册
 * @桓桓
 */

'use strict';
import React from 'react';
import {StyleSheet, Text, TextInput, TouchableOpacity, View, Keyboard} from 'react-native'
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view"
import loginStyle from '../../style/loginStyle'
import {FormValidation} from '../../utils/validation/FormValidation'
import {inject, observer} from 'mobx-react'

@inject('loginStore')
@observer
export default class Register extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            time: 60,
            codeBtnText: '获取验证码',

            avatar: '', // 头像
            nickname: '', // 昵称
            emp_no: '', // 手机号(账号) 注：mobile是企业联系人用的字段
            code: '', // 验证码
            password: '', // 密码
            password_confirm: '', // 确认密码
            secondary_password: '', // 支付密码
        }
    }

    componentDidMount(){
        
    }

    componentWillUnmount () {
        this.timer && clearInterval(this.timer);
    }
    
    // 获取验证码
    requestGetCodeSms = async () => {
        let {emp_no, time} = this.state
        if (emp_no == '') {
            ToastManager.message('请输入手机号');
            return
        }
        if (time < 60) return false
        let url = ServicesApi.SEND_SMS;
        let data = {
            mobile: emp_no,
            type: 1, // 1：注册时绑定手机号，2：验证码登录时获取验证码，3：忘记密码时验证手机号
            app_type: 2,  // 1货主  2承运商
        };
        let result = await Services.post(url, data);
        if (result.code == StatusCode.SUCCESS_CODE) {
            ToastManager.success('短信发送成功，请注意查收');
            this.countDown()
        } else {
            ToastManager.fail(result.msg);
            this.countDown()
        }
    };

    // 倒计时
    countDown = () => {
        let {time} = this.state
        this.timer = setInterval(()=> {
            if (time == 0){
                clearInterval(this.timer);
                this.setState({
                    time: 60,
                    codeBtnText: '获取验证码'
                })
            } else{
                this.setState({
                    time: time,
                    codeBtnText: time + '秒后重新获取'
                })
            }
            time--
        }, 1000)
    }

    onPressUpImg = async () => {
        let _result = await MediaManager.showActionPicker({
            includeBase64: true,
        });
        if (_result && _result.code === StatusCode.SUCCESS_CODE) {
            // ToastManager.loading('上传中...', {duration: 9999999});
            console.log('_result------------->', _result)
            const upRes = await Services.uploadQiNiu(_result.data);
            console.log('upRes------------->', upRes)
            if (upRes.code === StatusCode.SUCCESS_CODE) {
                ToastManager.hide();
                ToastManager.success('上传成功');
                // this.getLatestUserInfo()
                this.setState({avatar: ServicesApi.QI_NIU_HOST + upRes.data[0].key});
            } else {
                ToastManager.fail('上传失败');
            }
        }
    };

    // 发送请求
    onSubmit = async () => {
        Keyboard.dismiss();
        let {loginStore} = this.props;
        let {avatar, nickname, emp_no, code, password, password_confirm, secondary_password} = this.state;
        let url = ServicesApi.REGISTER;
        let data = {
            avatar,
            nickname,
            emp_no,
            code,
            password,
            password_confirm,
            app_type: 2,  // 1货主  2承运商
            secondary_password,
        };
        let result = await loginStore.doLogin(url, data);
        if (result.code == StatusCode.SUCCESS_CODE) {
            ToastManager.success(result.msg);
            RouterHelper.reset('', 'Tab');
        } else if (result.code === StatusCode.FAIL_CODE) {
            ToastManager.warn(result.msg);
        }
    };

    render() {
        let {codeBtnText, avatar, nickname, emp_no, code, password, password_confirm, secondary_password} = this.state;
        return (
            <PageContainer
                // fitNotchedScreen={Predefine.isNotchedScreen}
                style={styles.container}
            >
                <NavigationBar 
                    title={'注册'}
                    style={styles.navigationBar}
                />
                <KeyboardAwareScrollView
                    keyboardShouldPersistTaps={'handled'}
                    style={styles.contentBoxStyle}
                >
                    <ImageView
                        resizeMode={'cover'}
                        style={styles.backGroundImg}
                        source={Images.img_login_bg}
                    />
                    <View style={{
                        minHeight: SCREEN_HEIGHT-150,
                        marginBottom: 50,
                        justifyContent: 'space-between',
                    }}>
                        <View style={styles.box}>
                            <TouchableOpacity style={styles.avatarBox} onPress={() => this.onPressUpImg()}>
                                {
                                    avatar == '' 
                                    ?
                                    <ImageView
                                        resizeMode={'contain'}
                                        style={styles.avatarNull}
                                        source={Images.icon_plus}
                                    />
                                    :
                                    <ImageView
                                        resizeMode={'cover'}
                                        style={styles.avatar}
                                        source={{uri: avatar}}
                                    />
                                }
                            </TouchableOpacity>
                            <Text style={styles.avatarText} numberOfLines={1}>{avatar == '' && '请上传头像'}</Text>
                            <View style={styles.form}>
                                <View style={styles.inputLine}>
                                    <ImageView
                                        resizeMode={'contain'}
                                        style={styles.inputIcon}
                                        source={Images.icon_login_icon3}
                                    />
                                    <TextInput
                                        defaultValue={nickname}
                                        style={styles.input}
                                        placeholder={'请输入用户名'}
                                        placeholderTextColor={'#999'}
                                        onChangeText={(text) => this.setState({nickname: text})}
                                    />
                                </View>  
                                <View style={styles.inputLine}>
                                    <ImageView
                                        resizeMode={'contain'}
                                        style={styles.inputIcon}
                                        source={Images.icon_login_icon1}
                                    />
                                    <TextInput
                                        defaultValue={emp_no}
                                        style={styles.input}
                                        placeholder={'请输入手机号'}
                                        placeholderTextColor={'#999'}
                                        onChangeText={(text) => this.setState({emp_no: text})}
                                        keyboardType={'phone-pad'}
                                        maxLength={11}
                                    />
                                </View>
                                <View style={styles.inputLine}>
                                    <ImageView
                                        resizeMode={'contain'}
                                        style={styles.inputIcon}
                                        source={Images.icon_login_icon2}
                                    />
                                    <TextInput
                                        defaultValue={code}
                                        style={styles.input}
                                        placeholder={'请输入验证码'}
                                        placeholderTextColor={'#999'}
                                        keyboardType={'phone-pad'}
                                        onChangeText={(text) => this.setState({code: text})}
                                    />
                                    <TouchableOpacity style={styles.inputCodeBox} onPress={() => this.requestGetCodeSms()}>
                                        <Text style={styles.inputCode} numberOfLines={1}>{codeBtnText}</Text>
                                    </TouchableOpacity>
                                </View>   
                                
                                <View style={styles.inputLine}>
                                    <ImageView
                                        resizeMode={'contain'}
                                        style={styles.inputIcon}
                                        source={Images.icon_login_icon3}
                                    />
                                    <TextInput
                                        defaultValue={password}
                                        style={styles.input}
                                        placeholder={'请输入密码'}
                                        placeholderTextColor={'#999'}
                                        onChangeText={(text) => this.setState({password: text})}
                                        secureTextEntry={true}
                                    />
                                </View>   
                                <View style={styles.inputLine}>
                                    <ImageView
                                        resizeMode={'contain'}
                                        style={styles.inputIcon}
                                        source={Images.icon_login_icon3}
                                    />
                                    <TextInput
                                        defaultValue={password_confirm}
                                        style={styles.input}
                                        placeholder={'请确认密码'}
                                        placeholderTextColor={'#999'}
                                        onChangeText={(text) => this.setState({password_confirm: text})}
                                        secureTextEntry={true}
                                    />
                                </View>   
                                <View style={styles.inputLine}>
                                    <ImageView
                                        resizeMode={'contain'}
                                        style={styles.inputIcon}
                                        source={Images.icon_login_icon3}
                                    />
                                    <TextInput
                                        defaultValue={secondary_password}
                                        style={styles.input}
                                        placeholder={'请输入支付密码'}
                                        placeholderTextColor={'#999'}
                                        onChangeText={(text) => this.setState({secondary_password: text})}
                                        secureTextEntry={true}
                                    />
                                </View>   
                            </View>
                            <View style={styles.loginBtnBox}>
                                <Button
                                    style={styles.loginBtn}
                                    title={'下一步'}
                                    titleStyle={styles.loginBtnTitle}
                                    onPress={this.onSubmit}
                                    // onPress={() => RouterHelper.navigate('', 'Approve')}
                                />
                            </View>
                        </View>
                        
                    </View>
                    
                </KeyboardAwareScrollView>
            </PageContainer>
        );
    }
}
const DominantColor = '#00BFCC';
const SecondaryColor = '#E4E4E4';
const styles = StyleSheet.create({
    // 顶部
    navigationBar: {
        // backgroundColor: '#fff',
        // borderBottomWidth: 0,
    // marginTop: -88,
    },
    // 背景图
    backGroundImg: {
        zIndex: 0,
        position: 'absolute',
        width: SCREEN_WIDTH,
        height: SCREEN_WIDTH * (570 / 1125),
    },
    // 整体居中
    box: {
        alignItems: 'center',
    },
    // 图标
    avatarBox: {
        width: 80,
        height: 80,
        borderRadius: 10,
        backgroundColor: '#fff',
        marginTop: SCREEN_WIDTH * (570 / 1125) - 50,
        alignItems: 'center',
        justifyContent: 'center',
        elevation: 20, // 安卓
        shadowOffset: {width: 5, height: 5},
        shadowColor: '#C8C8C8',
        shadowOpacity: 1,
        shadowRadius: 10,
        marginBottom: 20,
    },
    avatar: {
        width: 80,
        height: 80,
        borderRadius: 10,
        overflow: 'hidden',
    },
    avatarNull: {
        width: 50,
        height: 50,
    },
    avatarText: {
        fontSize: 15,
        color: '#333',
    },
    // 密码登录/验证码登录
    header: {
        flexDirection: 'row',
        marginBottom: 20,
    },
    headerBox: {
        width: 100,
        height: 30,
        alignItems: 'center',
        justifyContent: 'center',
        borderBottomWidth: 2,
        borderBottomColor: SecondaryColor,
    },
    headerBoxAchieve: {
        borderBottomColor: DominantColor,
    },
    headerText: {
        color: '#BBB',
    },
    headerTextAchieve: {
        color: DominantColor,
    },
    // form
    form: {
        width: SCREEN_WIDTH,
        paddingHorizontal: 30,
        marginBottom: 50,
    },
    inputLine: {
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomWidth: Predefine.minPixel,
        borderBottomColor: '#C8C8C8',
    },
    inputIcon: {
        width: 14,
        height: 14,
        marginRight: 8,
    },
    input: {
        flex: 1,
        height: 50,
        paddingHorizontal: 0,
        paddingVertical: 0,
        fontSize: 14,
    },
    inputCodeBox: {
        paddingLeft: 5,
        borderLeftWidth: 1,
        borderLeftColor: DominantColor,
    },
    inputCode: {
        fontSize: 15,
        color: DominantColor,
    },
    // 按钮
    loginBtnBox: {
        marginBottom: 20,
        elevation: 20, // 安卓
        shadowOffset: {width: 1, height: 1},
        shadowColor: DominantColor,
        shadowOpacity: 0.5,
        shadowRadius: 5,
    },
    loginBtn: {
        width: SCREEN_WIDTH - 60,
        height: 36,
        backgroundColor: DominantColor,
        borderRadius: 18,
        paddingHorizontal: 0,
        paddingVertical: 0,
    },
    // bottom
    bottom: {
        width: SCREEN_WIDTH - 60,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 100,
    },
    bottomText: {
        fontSize: 14,
    },
    blueText: {
        color: '#0C81FF',
    },
});
